/**
 * 
 */
package com.xored.glance.search.engine;

import java.util.regex.Pattern;

/**
 * @author Yuri Strot
 * 
 */
public class SearchRule {

	/**
	 * @param text
	 * @param caseSensitive
	 * @param prefix
	 */
	public SearchRule(String text, boolean caseSensitive, boolean prefix) {
		this.text = text;
		this.caseSensitive = caseSensitive;
		this.prefix = prefix;
	}

	/**
	 * @return the prefix
	 */
	public boolean isPrefix() {
		return prefix;
	}

	/**
	 * @return the pattern
	 */
	public Pattern getPattern() {
		if (pattern == null) {
			pattern = SearchUtils.createPattern(text, caseSensitive, prefix);
		}
		return pattern;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (caseSensitive ? 1231 : 1237);
		result = prime * result + (prefix ? 1231 : 1237);
		result = prime * result + ((text == null) ? 0 : text.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SearchRule other = (SearchRule) obj;
		if (!isSettingsEqual(other))
			return false;
		return isTextEquals(other);
	}

	public boolean isSettingsEqual(SearchRule other) {
		if (other == null)
			return false;
		if (caseSensitive != other.caseSensitive)
			return false;
		if (prefix != other.prefix)
			return false;
		return true;
	}

	public boolean isTextEquals(SearchRule other) {
		if (other == null)
			return false;
		if (text == null) {
			if (other.text != null)
				return false;
		} else if (!text.equals(other.text))
			return false;
		return true;
	}

	private Pattern pattern;
	private String text;
	private boolean caseSensitive;
	private boolean prefix;

}
